2 + 2 # Add
3 - 4 # Subtract
5 * 2 # Multiply
4 / 2 # Divide
2 ^ 3 # Exponent
2 ** 3 # Exponent as well1: R Basics
Reading
From R Coding Basics: An Introduction to the Basics of Coding in R by Dr. Gaston Sanchez:
Topics
Mathematical operations
Operation precedence
Comments
Objects, variables, and assignments
Variable names and reserved words
Functions
Help Documentation
Packages
Mathematical Operations
- Common mathematical operations in R include:
Operation Precedence
- In R, operator precedence (from highest to lowest) is:
# Parenthesis
(2 + 3) * 4
# Exponent
2 ^ 3
2 ** 3
# Multiply and divide (from left to right)
5 * 2
4 / 2
# Add and subtract
2 + 2
3 - 4💻 Hands-On
Evaluate the following expressions in R:
\(19 - 3 \times 6\)
\(20 - 2 \times 3^2 + 11\)
\(3 + 8 \div 2 \times 2\)
\(7 - (5 \times 3 + 2^3)\)
19 - 3 * 6[1] 1
20 - 2 * 3^2 + 11[1] 13
3 + 8 / 2 * 2[1] 11
7 - (5 * 3 + 2^3)[1] -16
Object, Variable, and Assignment
An object is anything that stores values or instructions.
A variable is a name associated to an object so that we can access the object in memory.
A variable can be created using the assignment operator
<-(left arrow) or the equal sign=.
# 100 is an object itself
100
# We name this object 'eagles'
eagles <- 100
# The variable 'eagles' allows us to access the object 100
eagles💻 Hands-On
Create the following variables:
yearthat stores the value2026pricethat stores the value5.5scorethat stores the value93
year <- 2026
price <- 5.5
score <- 9.3Variable Names
- Variable names are case-sensitive.
# These names are NOT the same
eagles
Eagles
EAGLES
eaGleS
EagLEs
EaGlEs💻 Hands-On
Run the following code in the console. What does it return?
EAGLES <- 123
EaglesSince variable names are case-sensitive, EAGLES and Eagles are different. In this case, we created EAGLES but not Eagles so R will throw an error.
EAGLES <- 123
EaglesError: object 'Eagles' not found
Variable Names
A variable name must start with a letter or a period (not recommended). The rest can only consist of letters
a-z, A-Z, numbers0-9, underscores_, and periods.A variable name cannot be a reserved word (
TRUE,FALSE,if,for,while, etc.)
# Valid variable names
age
height_cm1
weight2.kg
# Valid but not recommended
.data
TrueReserved Words
- Reserved words are words with special meaning and cannot be used as variable names.
if, else, for, while, function
break, stop, continue, next
TRUE, FALSE
NULL, NA, Inf, NaN💻 Hands-On
The following R code attempts to create variables. Run each line in the console and explain why the variable name is invalid.
9null <- 5
null%9 <- 5
null 9 <- 5
_null9 <- 5
null,9 <- 5
NULL <- 5Note that all given variable names are invalid. See below for the explanation.
9null <- 5 # variable name cannot start with a number
null%9 <- 5 # variable name cannot contain any percentage
null 9 <- 5 # variable name cannot contain any space
_null9 <- 5 # variable name cannot start with an underscore
null,9 <- 5 # variable name cannot contain any comma
NULL <- 5 # variable name cannot be a reserved wordNaming Styles
Three common naming styles for variables include
eagles_green_swag # snake case
eaglesGreenSwag # camel case
eagles.green.swag # period case💻 Hands-On
Create three variables that represent the phrase “Crimson Roll Tide” using the three naming styles.
[Tidyverse style guide]{https://style.tidyverse.org/syntax.html) recommends the snake case, which is what I tend to use as well!
crimson_roll_tide # snake case
crimsonRollTide # camel case
crimson.roll.tide # period caseFunctions
A function is a collection of R code to perform a complex task or obtain certain results.
R has many useful built-in functions.
# Absolute value, sign function, and squared root
abs, sign, sqrt
# Rounding of numbers
round, floor, ceiling, trunc, signif
# Logarithms and Exponentials
exp, log, expm1, log1p
# Combination and factorial
choose, factorial, lchoose, lfactorial
# Trigonometric and hyperbolic functions
cos, sin, tan, cospi, sinpi, tanpi, acos, asin, atan
cosh, sinh, tanh, acosh, asinh, atanh
# Beta and gamma functions
beta, lbeta, gamma, lgamma, digamma, trigamma, psigamma💻 Hands-On
Try the following code in the console.
abs(-7) # absolute value
sqrt(25) # squared root
exp(3) # exponential
log(8) # natural log
factorial(6) # 1 x 2 x 3 x 4 x 5 x 6abs(-7) # absolute value[1] 7
sqrt(25) # squared root[1] 5
exp(3) # exponential[1] 20.08554
log(8) # natural log[1] 2.079442
factorial(6) # 1 x 2 x 3 x 4 x 5 x 6[1] 720
Getting Help
- If we want to learn more about a function, we can refer to its help documentation.
# Using the operator '?'
?abs
?sqrt
# Using the help() function
help(abs)
help(sqrt)💻 Hands-On
Use the help documentation to explain the purpose of the following functions.
sign(-17)
log1p(3)
choose(5, 2)To get the help documentation of the functions, we can use ? or help()
?sign
help(sign)
?log1p
help(log1p)
?choose
help(choose)The functions do the following
sign(-17) # give -1 for negative number and 1 for positive number[1] -1
log1p(3) # compute log(1 + 3)[1] 1.386294
choose(5, 2) # compute combination coefficient 5C2 [1] 10
💻 Hands-On
What does the following code do? Use the help documentation of round() to confirm your guess/observation.
round(6.267)
round(6.267, digits = 1)
round(6.267, 1)
round(6.267, digits = 2)
round(6.267, 2)To get the help documentation of round(), we can use ? or help(). It is actually pretty self-explanatory!
?round
help(round)The given code does the following
# Round to the whole number (digits = 0)
round(6.267)[1] 6
# Round to 1 decimal place
round(6.267, digits = 1)[1] 6.3
# Round to 2 decimal places
round(6.267, digits = 2)[1] 6.27
Packages
A package is a collection of functions and data for specific purpose.
Most developers make their packages freely available on the Comprehensive R Archive Network (CRAN).
# Install a package
install.packages("bannerCommenter")
# Load an installed package
library(bannerCommenter)
library("bannerCommenter")
# Uninstall a package
remove.packages("bannerCommenter")
Comments
Comments are notes to explain what the code does.
In R, comments are created using a hash
#.On a line, everything after a hash will be ignored. In other words, even if the comments contain some code, it will not be executed.
The keyboard short cut to comment out blocks of code is
CommandorCtrl+Shift+c💻 Hands-On
Run the following code in the console and add a comment describing the output.